﻿using System.Reflection; 

namespace Microsoft.Extensions.DependencyInjection;

[AttributeUsage(AttributeTargets.Class)]
public class InjectionAttribute: Attribute
{
    public Type? ServiceType { get; set; }
    public ServiceLifetime Lifetime { get; set; } = ServiceLifetime.Scoped;
}

public static class InjectionIServiceCollectionExtensions
{
    public static IServiceCollection AddServiceByInjection<T>(this IServiceCollection services)
    {
        var serviceTypes = typeof(T).Assembly.GetTypes()
            .Where(a => a.IsClass)
            .Where(a => a.GetCustomAttribute<InjectionAttribute>() != null)
            .Where(a => !a.IsAbstract);

        foreach (var item in serviceTypes)
        {
            var injection = item.GetCustomAttribute<InjectionAttribute>();
            if (injection!.ServiceType == null)
            {
                services.Add(new ServiceDescriptor(item, item, injection.Lifetime));
            }
            else
            {
                services.Add(new ServiceDescriptor(injection!.ServiceType, item, injection.Lifetime));
            }
        }
        return services;
    }
}